import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, message} from 'antd';
import {FORM_OPTIONS, TABLE, PAGINATION_OPTIONS, PAGE, COMMON_TABLE_EMPTY_TEXT, COMMON_TABLE_QUERY_FAIL_TEXT} from '../../constants';
import TextInput from 'Shared/components/TextInput';
import SelectAlert from '../SelectAlert';
import styles from './select-panel.css';
import {formatMessage} from '../localize';
import {uniqBy} from 'lodash';

const FormItem = Form.Item;
const EMPTY_ARRAY = [];

class DutyUnitSelectPanel extends PureComponent {
    state = {
        condition: {
            pageIndex: PAGE.index,
            pageSize: PAGE.smallSize
        },
        currentCondition: {},
        keys: EMPTY_ARRAY,
        rows: EMPTY_ARRAY,
        loading: false,
        data: EMPTY_ARRAY,
        total: 0,
        error: false
    };

    handleConditionChange = (value, name) => this.setState({condition: Object.assign({}, this.state.condition, {[name]: value})});

    handleQueryBtnClick = () => this.onQuery(Object.assign({}, this.state.currentCondition, this.state.condition, {pageIndex: PAGE.index}));

    handleFilterPressEnter = (value, name) => this.setState(() => ({condition: Object.assign({}, this.state.condition, {[name]: value})}), this.handleQueryBtnClick);

    handleTableChange = (pagination, filters, sorter) => {
        const query = {
            sortField: null,
            isDesc: null
        };
        if(pagination.pageSize)
            query.pageSize = pagination.pageSize;
        if(pagination.current)
            query.pageIndex = pagination.current - 1;
        if(sorter.order && sorter.field) {
            query.sortField = sorter.field;
            query.isDesc = sorter.order === 'descend';
        }
        this.onQuery(Object.assign({}, this.state.currentCondition, query));
    };

    // eslint-disable-next-line react/sort-comp
    onQuery = conditions => {
        this.setState({loading: true});
        this.props.getDutyUnits(Object.assign(conditions, this.props.isCountry ? {
            ...this.props.conditions,
            type: 2
        } : this.props.conditions)).then(result => this.setState({
            loading: false,
            error: result.ok,
            data: result.ok ? result.data.content : EMPTY_ARRAY,
            total: result.ok ? result.data.totalElements : 0,
            currentCondition: conditions
        }));
    };

    isSortOrder = propName => this.state.currentCondition.sortField === propName && (this.state.currentCondition.isDesc ? 'descend' : 'ascend');

    onSelectChange = (keys, rows) => this.setState({
        keys,
        rows: uniqBy(this.state.rows.concat(rows), 'id').filter(row => keys.includes(row.id))
    });

    onClear = () => this.setState({
        keys: [],
        rows: []
    });

    onCloseTag = id => this.setState({
        keys: this.state.keys.filter(key => key !== id),
        rows: this.state.rows.filter(row => row.id !== id),
    });

    onSelect = () => {
        if(!this.state.keys.length)
            return message.warn(formatMessage({
                id: 'dutyUnitSelectPanel.validMessage1',
                defaultMessage: '请选择'
            }) + this.props.titleName);
        this.props.onSelect(this.props.multi ? this.state.rows : this.state.rows[0]);
    };

    render() {
        const columns = [{
            title: formatMessage({
                id: 'dutyUnitSelectPanel.name',
                defaultMessage: '名称'
            }),
            sorter: true,
            dataIndex: 'name',
            sortOrder: this.isSortOrder('name')
        }].concat(this.props.columns.map(col => {
            if(col.sorter)
                col.sortOrder = this.isSortOrder(col.dataIndex);
            return col;
        }));
        if(!this.props.isCountry)
            columns.splice(0, 0,
                {
                    title: formatMessage({
                        id: 'dutyUnitSelectPanel.code',
                        defaultMessage: '编号'
                    }),
                    dataIndex: 'code',
                    sorter: true,
                    sortOrder: this.isSortOrder('code')
                });
        if(this.props.isCountry)
            columns.splice(1, 0,
                {
                    title: formatMessage({
                        id: 'dutyUnitSelectPanel.chineseName',
                        defaultMessage: '中文名称'
                    }),
                    dataIndex: 'chineseName',
                    sorter: true,
                    sortOrder: this.isSortOrder('chineseName')
                });
        const pagination = {
            total: this.state.total,
            current: this.state.currentCondition.pageIndex + 1,
            pageSize: this.state.currentCondition.pageSize,
            ...PAGINATION_OPTIONS
        };

        const onRow = this.props.multi ? null : record => ({onDoubleClick: () => this.props.onSelect(record)});

        const rowSelection = {
            type: this.props.multi ? 'checkbox' : 'radio',
            fixed: true,
            selectedRowKeys: this.state.keys,
            getCheckboxProps: record => ({
                disabled: this.props.currentSelectRowKeys.some(item => item === record.id)
            }),
            onChange: this.onSelectChange
        };

        const Alert = this.props.multi ? SelectAlert.Multi : SelectAlert;

        return (
            <div>
                <Row className="form-standard">
                    {!this.props.isCountry && <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'dutyUnitSelectPanel.code',
                            defaultMessage: '编号'
                        })} {...FORM_OPTIONS.item}>
                            <TextInput name="code" value={this.state.condition.code}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.handleConditionChange}/>
                        </FormItem>
                    </Col>}
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'dutyUnitSelectPanel.name',
                            defaultMessage: '名称'
                        })} {...FORM_OPTIONS.item}>
                            <TextInput name="name" value={this.state.condition.name}
                                onPressEnter={this.handleFilterPressEnter}
                                onBlur={this.handleConditionChange}/>
                        </FormItem>
                    </Col>
                    {this.props.isCountry &&
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'dutyUnitSelectPanel.chineseName',
                                defaultMessage: '中文名称'
                            })} {...FORM_OPTIONS.item}>
                                <TextInput name="chineseName" value={this.state.condition.chineseName}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleConditionChange}/>
                            </FormItem>
                        </Col>}
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button type="primary" loading={this.state.loading} onClick={this.handleQueryBtnClick}>{formatMessage({
                            id: 'dutyUnitSelectPanel.query',
                            defaultMessage: '查询'
                        })}</Button>
                    </Col>
                </Row>
                <Divider className={styles.divider}/>
                <Alert key="alert" data={this.state.rows.map(item => ({
                    value: item.id,
                    text: item.code
                }))} onConfirm={this.onSelect} onDelete={this.onCloseTag} onDeleteAll={this.onClear}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={this.state.data}
                    columns={columns}
                    onRow={onRow}
                    rowSelection={rowSelection}
                    loading={this.state.loading}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    {...TABLE}
                    locale={{emptyText: this.state.error ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT}}/>
            </div>
        );
    }
}


import * as api from './api';

const EMPTY_OBJECT = {};

DutyUnitSelectPanel.defaultProps = {
    multi: false,
    getDutyUnits: api.getDutyUnits,
    conditions: EMPTY_OBJECT,
    columns: EMPTY_ARRAY,
    currentSelectRowKeys: EMPTY_ARRAY,
    isCountry: false
};

DutyUnitSelectPanel.propTypes = {
    /**
    * 选中后回调，return multi ? object : array
    */
    onSelect: PropTypes.func.isRequired,
    /**
     * 增加展示列，antd column
     */
    columns: PropTypes.array,
    /**
     * 增加展示列，antd column
     */
    conditions: PropTypes.object,
    /**
     * 增加默认查询条件，界面不做展示
     */
    currentSelectRowKeys: PropTypes.array,
    /**
     * 查询责任单位API，为空取默认API
     */
    getDutyUnits: PropTypes.func,
    /**
     * 查询查询国家
     */
    isCountry: PropTypes.bool,
    /**
     * 多选，default false
     */
    multi: PropTypes.bool,
    //节点标题
    titleName: PropTypes.string,
};

export default DutyUnitSelectPanel;
